//
//  BaseViewController.m
//  YiBaoStore
//
//  Created by 毛云河 on 2018/10/1.
//  Copyright © 2018年 小河. All rights reserved.
//

#import "BaseViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <CoreLocation/CoreLocation.h>
#import <AVFoundation/AVCaptureDevice.h>


@interface BaseViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@end

@implementation BaseViewController

//视图即将消失的时候关闭键盘
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication].keyWindow endEditing:YES];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    // 禁用返回手势
    if ([self.navigationController respondsToSelector:@selector(interactivePopGestureRecognizer)]) {
        self.navigationController.interactivePopGestureRecognizer.enabled = NO;
    }
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    IQKeyboardManager *keyboardManager = [IQKeyboardManager sharedManager];
    keyboardManager.shouldResignOnTouchOutside = YES;
    [keyboardManager setToolbarDoneBarButtonItemText:@"完成"];
    keyboardManager.keyboardDistanceFromTextField = 0;
    [self initNavView];
}

#pragma mark - 设置导航
- (void)initNavView
{
    self.bgNavView = [[UIView alloc]init];
    if (@available(iOS 11.0, *))
    {
        self.bgNavView.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight_xs);
    } else {
        // Fallback on earlier versions
        self.bgNavView.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight);
    }
    self.bgNavView.backgroundColor = NavBgColor;
    [self.view addSubview:self.bgNavView];
    
    self.titLabel = [[UILabel alloc]init];
    if (@available(iOS 11.0, *))
    {
        self.titLabel.frame = CGRectMake((SCREENWIDTH-200)/2, TopStatusHeight_xs+33, 200, 18);
    } else {
        // Fallback on earlier versions
        self.titLabel.frame = CGRectMake((SCREENWIDTH-200)/2, TopStatusHeight+33, 200, 18);
    }
    [self.bgNavView addSubview:self.titLabel];
    self.titLabel.textAlignment = 1;
    self.titLabel.textColor = BlackTextColor;
    self.titLabel.font = FontMediumWithSize(18);
    
    //当不是跟控制器的时候才添加返回按钮
    if (self.navigationController.viewControllers.count > 1)
    {
        self.navigationController.hidesBottomBarWhenPushed = YES;
        self.leftIcon = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"back"]];
        [self.bgNavView addSubview:self.leftIcon];
        if (@available(iOS 11.0, *))
        {
            self.leftIcon.frame = CGRectMake(15, 35+TopStatusHeight_xs, 18, 14);
        } else {
            // Fallback on earlier versions
            self.leftIcon.frame = CGRectMake(15, 35+TopStatusHeight, 18, 14);
        }
        
    }
    
    self.rightIcon = [[UIImageView alloc]init];
    [self.bgNavView addSubview:self.rightIcon];
    if (@available(iOS 11.0, *))
    {
        self.rightIcon.frame = CGRectMake(SCREENWIDTH-39, 33+TopStatusHeight_xs, 18, 18);
    } else {
        // Fallback on earlier versions
        self.rightIcon.frame = CGRectMake(SCREENWIDTH-39, 33+TopStatusHeight, 18, 18);
    }
    self.rightIcon.hidden = YES;
    
    self.leftBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 11.0, *))
    {
        self.leftBtn.frame = CGRectMake(0, 20+TopStatusHeight_xs, 60, 40);
    } else {
        // Fallback on earlier versions
        self.leftBtn.frame = CGRectMake(0, 20+TopStatusHeight, 60, 40);
    }
    [self.bgNavView addSubview:self.leftBtn];
    [self.leftBtn addTarget:self action:@selector(leftBtnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    
    self.rightBtn = [UIButton buttonWithType:UIButtonTypeSystem];
    if (@available(iOS 11.0, *))
    {
        self.rightBtn.frame = CGRectMake(SCREENWIDTH-60, 20+TopStatusHeight_xs, 60, 40);
    } else {
        // Fallback on earlier versions
        self.rightBtn.frame = CGRectMake(SCREENWIDTH-60, 20+TopStatusHeight, 60, 40);
    }
    [self.bgNavView addSubview:self.rightBtn];
    self.rightBtn.hidden = YES;
    [self.rightBtn addTarget:self action:@selector(rightBtnClick:) forControlEvents:UIControlEventTouchUpInside];
}

- (void)leftBtnBackClick:(UIButton *)sender
{
    UIViewController * controller=[self.navigationController.viewControllers objectAtIndex:0];
    if(controller == self) {
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
    }
    else {
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)setNaviWith:(NSString *)name
{
    self.bgNavView.hidden = YES;
    UIView *navi = [UIView new];
    if (@available(iOS 11.0, *)) {
        navi.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight_xs);
    } else {
        // Fallback on earlier versions
        navi.frame = CGRectMake(0, 0, SCREENWIDTH, TopBarHeight);
    }
    navi.tag = 20;
    navi.backgroundColor = TotalWhite;
    [self.view addSubview:navi];
    
    UIImageView *leftIV = [UIImageView new];
    leftIV.frame = CGRectMake(15, navi.height-15-18, 18, 14);
    leftIV.image = [UIImage imageNamed:@"back"];
    [navi addSubview:leftIV];
    
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(8, navi.height-40, 32, 28);
    leftBtn.backgroundColor = ClearColor;
    [leftBtn addTarget:self action:@selector(leftBtnBackClick:) forControlEvents:UIControlEventTouchUpInside];
    [navi addSubview:leftBtn];
    
    UILabel *titleLab = [UILabel new];
    CGFloat left = 30+18;
    titleLab.frame = CGRectMake(left, navi.height-13-18, SCREENWIDTH-96, 18);
    titleLab.textColor = titleColor;
    titleLab.tag = 30;
    titleLab.font = FontSemiboldSize(18);
    titleLab.attributedText = [TTKUtil getAtttributeStringWithLineSpace:0 kern:-0.9 and:name];
    titleLab.textAlignment = NSTextAlignmentCenter;
    [navi addSubview:titleLab];
}


- (void)rightBtnClick:(UIButton *)sender {
}

- (void)ShowHUDWithMessage:(NSString *)message
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    hud.mode = MBProgressHUDModeCustomView;
    hud.bezelView.backgroundColor = UIColorFromHex(0xFF9D9D9D);
    hud.contentColor = [UIColor whiteColor];
    hud.label.text = NSLocalizedString(message, nil);
    hud.label.font = FontWithSize(12);
    [hud hideAnimated:YES afterDelay:HUDTime];
}

#pragma mark --- 拍照
- (void)takePhoto
{
    [self.view endEditing:YES];
    
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"选择图片", nil) message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *ok = [UIAlertAction actionWithTitle:NSLocalizedString(@"相机", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"确定");
        if (TARGET_IPHONE_SIMULATOR) {
            NSLog(@"模拟器无拍照功能");
        }else{
            //相机权限
            AVAuthorizationStatus authStaus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
            if (authStaus ==AVAuthorizationStatusRestricted//此应用程序没有被授权访问的照片数据。可能是家孩子那个控制权限
                ||authStaus==AVAuthorizationStatusDenied)//用户已经明确否认了这一照片数据的应用程序访问
            {
                //无权限 引导去开启
                NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
                if ([[UIApplication sharedApplication]canOpenURL:url]) {
                    [[UIApplication sharedApplication]openURL:url];
                }
                
            }
            if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) return ;
            
            //创建图片选择控制器
            UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
            ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
            ipc.delegate = self;
            
            [self presentViewController:ipc animated:YES completion:nil];
            
        }
    }];
    UIAlertAction *photo = [UIAlertAction actionWithTitle:NSLocalizedString(@"相册", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        //权限
        ALAuthorizationStatus author = [ALAssetsLibrary authorizationStatus];
        if (author==kCLAuthorizationStatusRestricted||author==kCLAuthorizationStatusDenied) {
            NSURL *url = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
            if ([[UIApplication sharedApplication]canOpenURL:url]) {
                [[UIApplication sharedApplication]openURL:url];
            }
            
        }
        if (![UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
            return ;
        UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
        ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        ipc.delegate = self;
        [self presentViewController:ipc animated:YES completion:nil];
        
    }];
    UIAlertAction *cancel = [UIAlertAction actionWithTitle:NSLocalizedString(@"取消", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"取消");
    }];
    [alert addAction:ok];
    [alert addAction:photo];
    [alert addAction:cancel];
    [self presentViewController:alert animated:YES completion:^{
    }];
}

#pragma mark -- imageController delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    
//    if (image.imageOrientation == UIImageOrientationRight) {
//        image = [UIImage imageWithCGImage:image.CGImage scale:0.5 orientation:UIImageOrientationUp];
//    }
    if (self.photoBlock) {
        self.photoBlock(image);
    }
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)changeShopState
{
    //0 表示正常店铺，10：待审核， 30： 待小程序授权（响应结果中的扩展字段attributes中会放入 auth_url 字段即授权链接）
    [[HttpRequest currentHttpRequest]postPath:ShopState_API params:nil resultBlock:^(id Data, MsgModel *msgModel) {
        NSString *shopStatus = [NSString stringWithFormat:@"%@",Data[@"storeStatusCode"]];
        
        if ([shopStatus isEqualToString:@"30"]) {
            [self.navigationController pushViewController:[AuthorBlindViewController new] animated:YES];
        }else if([shopStatus isEqualToString:@"0"])
        {
            MYHTabBarController *tab = [MYHTabBarController new];
            AppDelegate* app = (AppDelegate *)[UIApplication sharedApplication].delegate;
            app.window.rootViewController = tab;
        }
    }];
}

- (void)hideHUD {
    for (id view in [UIApplication sharedApplication].keyWindow.subviews) {
        if ([view isKindOfClass:[MBProgressHUD class]]) {
            MBProgressHUD *hud = view;
            [hud hideAnimated:YES];
        }
    }
}


#pragma mark - 友盟分享(分享图片)
- (void)sharkImageUMWith:(NSInteger)inter withImage:(UIImage *)image
{
    //0.预先设置分享类型
    UMSocialPlatformType type;
    if (inter == 1)
    {//微信好友
        type = UMSocialPlatformType_WechatSession;
        if ([[UMSocialManager defaultManager]isInstall:UMSocialPlatformType_WechatSession]==NO)
        {
            NSLog(@"未安装微信");
        }
    }
    else
    {//微信朋友圈
        type = UMSocialPlatformType_WechatTimeLine;
        if ([[UMSocialManager defaultManager]isInstall:UMSocialPlatformType_WechatTimeLine]==NO)
        {
            NSLog(@"没有朋友圈");
        }
    }
    
    //1.创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //2.创建分享内容的类型(文本，图片，网页)
    //图片内容对象
    UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];
    //如果有缩略图，则设置缩略图
    //shareObject.thumbImage = [UIImage imageNamed:@"icon"];
    [shareObject setShareImage:image];
    
    //3.分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //4.调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id data, NSError *error)
     {
         if (error)
         {
             UMSocialLogInfo(@"************Share fail with error %@*********",error);
             if (error.code==2008)
             {
                 [TTKUtil hudShowMessage:@"您未安装此应用"];
             }
             else if (error.code == 2009)
             {
                 [TTKUtil hudShowMessage:@"取消分享"];
             }
             
         }else{
             if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                 UMSocialShareResponse *resp = data;
                 //分享结果消息
                 UMSocialLogInfo(@"response message is %@",resp.message);
                 //第三方原始返回的数据
                 UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
             }else{
                 UMSocialLogInfo(@"response data is %@",data);
             }
         }
         
     }];
}

#pragma mark - 友盟分享网页
- (void)shareHtmlWithType:(NSInteger)shareType title:(NSString *)title descr:(NSString *)descr imageUrl:(NSString *)imageurl shareURL:(NSString *)shareURL
{
    //分享地方
    UMSocialPlatformType type = 0;
    if (shareType == 1)
    {//微信好友
        if ([[UMSocialManager defaultManager]isInstall:UMSocialPlatformType_WechatSession] == NO)
        {
            NSLog(@"没有安装微信");
        }else
        {
            type = UMSocialPlatformType_WechatSession;
        }
    }
    else
    {//微信朋友圈
        if ([[UMSocialManager defaultManager]isInstall:UMSocialPlatformType_WechatTimeLine]==NO)
        {
            NSLog(@"没有朋友圈");
        }
        else
        {
            type = UMSocialPlatformType_WechatTimeLine;
        }
    }
    
//    title = IsEmptyStr(self.sharkTitle)?@"淘淘课，新知识分享":self.sharkTitle;
//    descr = IsEmptyStr(self.sharkDescribe)?@"让知识连接你我他":self.sharkDescribe;
//    webpageUrl = IsEmptyStr(self.sharkURL)?self.webView.request.URL.absoluteString:self.sharkURL;
    
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    //创建网页内容对象
    // NSString* thumbURL =  _werWeiMaUrl;

    // UIImage *imageIcon = IsEmptyStr(self.sharkIconImage)?[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:@"https://od-prod-static.oss-cn-shanghai.aliyuncs.com/default/logo/logo.png"]]]:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:self.sharkIconImage]]];
    
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:descr thumImage:imageurl];
    //设置网页地址
    shareObject.webpageUrl = shareURL;
    shareObject.title = title;
    
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享
    [[UMSocialManager defaultManager]shareToPlatform:type messageObject:messageObject currentViewController:self completion:^(id result, NSError *error)
     {
         if (error)
         {
             if (error.code==2008)
             {
                 [TTKUtil hudShowMessage:@"您未安装此应用"];
             }
             else if (error.code == 2009)
             {
                 [TTKUtil hudShowMessage:@"取消分享"];
             }
             UMSocialLogInfo(@"************Share fail with error %@*********",error);
         }else
         {
             if ([result isKindOfClass:[UMSocialShareResponse class]])
             {
                 [TTKUtil hudShowMessage:@"分享成功"];
                 UMSocialShareResponse *resp = result;
                 //分享结果消息
                 UMSocialLogInfo(@"response message is %@",resp.message);
                 //第三方原始返回的数据
                 UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
             }
             else
             {
                 UMSocialLogInfo(@"response data is %@",result);
             }
         }
     }];
}

#pragma mark - 保存海报到相册
- (void)saveImageToPhotos:(UIImage*)savedImage
{
    UIImageWriteToSavedPhotosAlbum(savedImage, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image: (UIImage *) image didFinishSavingWithError: (NSError *) error contextInfo: (void *) contextInfo
{
    if(error != NULL)
    {
        [self ShowHUDWithMessage:@"保存失败"];
    }
    else
    {
        [self ShowHUDWithMessage:@"保存成功，快去发给好友吧"];
    }
}

- (void)showHUDStyleSolidColor
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:[UIApplication sharedApplication].keyWindow animated:YES];
    //修改样式，否则等待框背景色将为半透明
    hud.bezelView.style = MBProgressHUDBackgroundStyleSolidColor;
    //设置等待框背景色为黑色
    hud.bezelView.backgroundColor = RGBACOLOR(0, 0, 0, 0.8);
    hud.removeFromSuperViewOnHide = YES;
    
    //设置菊花框为白色
    [UIActivityIndicatorView appearanceWhenContainedIn:[MBProgressHUD class], nil].color = [UIColor whiteColor];
    [[UIApplication sharedApplication].keyWindow addSubview:hud];
    [hud showAnimated:YES];
}

// 以图片中心为中心，以最小边为边长，裁剪正方形图片
-(UIImage *)cropSquareImage:(UIImage *)image
{
    CGImageRef sourceImageRef = [image CGImage];//将UIImage转换成CGImageRef
    
    CGFloat _imageWidth = image.size.width * image.scale;
    CGFloat _imageHeight = image.size.height * image.scale;
    
    CGFloat _width = _imageWidth > _imageHeight ? _imageHeight : _imageWidth;
    CGFloat _offsetX = (_imageWidth - _width) / 2;
    CGFloat _offsetY = (_imageHeight - _width) / 2;
    
    CGRect rect = CGRectMake(_offsetX, _offsetY, _width, _width);
    CGImageRef newImageRef = CGImageCreateWithImageInRect(sourceImageRef, rect);//按照给定的矩形区域进行剪裁
    UIImage *newImage = [UIImage imageWithCGImage:newImageRef];
    
    return newImage;
}



@end
